package com.gome.ocean.service.utils;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gome.ocean.dao.model.authority.Function;
import com.gome.ocean.dao.model.authority.RoleFunction;
import com.gome.ocean.dao.model.authority.User;
import com.gome.ocean.dao.model.reqres.UserFunctionTable;
import com.gome.ocean.service.authority.FunctionService;
import com.gome.ocean.service.authority.RoleFunctionService;
import com.google.common.collect.Lists;

/**
 * Created by liuqingxia on 2016/6/2.
 */
@Component
public class UserFuncTableBuilder {

    private static final Logger LOG = LoggerFactory.getLogger(UserFuncTableBuilder.class);

    @Autowired
    private FunctionService     functionService;
    @Autowired
    private RoleFunctionService roleFunctionService;

    public UserFunctionTable build(User user) {
        UserFunctionTable userFuncTable = new UserFunctionTable(user);
        try {
            Long roleId = user.getRoleId();
            List<RoleFunction> roleFunctionList = roleFunctionService.findRoleFunctionByRoleId(roleId);
            List<Long> ids = extractFuncIds(roleFunctionList);
            List<Function> functions = functionService.findFunctionsByIds(ids);
            userFuncTable.putFunction(functions);
        } catch (Exception e) {
            LOG.error("构造UserFunctionTable异常：" + e.getMessage(), e);
        }
        return userFuncTable;
    }

    private List<Long> extractFuncIds(List<RoleFunction> roleFunctions) {
        List<Long> ids = Lists.newArrayList();
        for (RoleFunction roleFunction : roleFunctions) {
            ids.add(roleFunction.getFuncid());
        }
        return ids;
    }
}
